from typing import Dict, Union
from ..utility import db_data_tool
from ..config import mdb
import asyncio


class DBCache:
    def __init__(self, db, load_sql):
        self.db = db
        self.load_sql = load_sql
        self.cache = {}

    async def load(self):
        self.cache = db_data_tool.dict_list2ddict(dlist=await mdb.query(self.load_sql), parse_col_name='id')

    def set(self, data: Dict[int, dict]):
        self.cache.update(data)

    def get(self, keys: list):
        for key in keys:
            return self.cache[key]

    def get_all(self):
        return list(self.cache.values())


# sql_load_all_element = '''
#                 select e.*, IFNULL(frame.element_name, '') as frame_name from test_element e
#                 left join test_element frame on frame.id=e.frame_id
#                 '''
# element_cache = DBCache(mdb, sql_load_all_element)
# asyncio.get_event_loop().run_until_complete(element_cache.load())
# case_cache = DBCache(mdb)
# job_cache = DBCache(mdb)

